﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FaceWebServer.DB.User;
using FaceWebServer.Interface;
using Microsoft.EntityFrameworkCore;

namespace FaceWebServer.Service
{
    /// <summary>
    /// 网址管理员操作服务
    /// </summary>
    public class UserService : BaseService, IUserService
    {
         
        public UserService(DbContext context) : base(context)
        {
            
        }

        public UserDetail GetCurrentUser()
        {
            return CurrentUser;
        }

        public DbSet<UserDetail> GetUserDBSet()
        {
            return this.Context.Set<UserDetail>();
        }

        

        public UserDetail UserLogin(string username, string password)
        {
            var users = Query<UserDetail>(x => x.UserName == username).ToList();
            if (users.Count != 1)
            {
                throw new ServiceException(1, "没有找到此用户！");
            }
            var user = users.First();
            if (user.UserName.Equals(username) && user.UserPassword.Equals(password))//应该数据库
            {
                user.LogTime = DateTime.Now;
                user.OnlineTime = DateTime.Now;

                CurrentUser = user;
                AddUserLog("登陆", "通过UI界面登陆");
                Commit();//更新到数据库
                return user;
            }
            else
            {
                throw new ServiceException(2, "用户名或密码错误！");
            }
        }


        /// <summary>
        /// 更新用户在线时间
        /// </summary>
        /// <returns></returns>
        public UserDetail UpdateUserOnlineTime(int id)
        {
            var user = Find<UserDetail>(id);

            if (user != null)//应该数据库
            {
                user.OnlineTime = DateTime.Now;
                Update<UserDetail>(user);
                return user;
            }
            else
            {
                throw new ServiceException(1, "用户已失效！");
            }
        }
    }
}
